package com.company.network.enviroment;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;

import android.content.Context;
import android.os.Bundle;
import android.widget.Toast;

import com.company.network.R;
import com.company.network.utils.SPUtils;

public class EnvironmentActivity extends AppCompatActivity {

    public static final String NET_KEY = "net_address";

    private static final String NET_ADDRESS_VALUE_KEY = "net_address_value_key";

    //当前环境线上地址
    public static String sCurEnv = "1";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_environment);
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.content, new MyPreferenceFragment()).commit();
        Object changeValue = SPUtils.get(this, NET_ADDRESS_VALUE_KEY, "1");
        sCurEnv = String.valueOf(changeValue);
    }

    public static class MyPreferenceFragment extends PreferenceFragmentCompat implements Preference.OnPreferenceChangeListener {

        @Override
        public void onCreatePreferences(Bundle bundle, String s) {
            addPreferencesFromResource(R.xml.settings_container);
            findPreference(NET_KEY).setOnPreferenceChangeListener(this);
        }

        @Override
        public boolean onPreferenceChange(Preference preference, Object o) {
            if (!sCurEnv.equalsIgnoreCase(String.valueOf(o))) {
                SPUtils.put(preference.getContext(), NET_ADDRESS_VALUE_KEY, String.valueOf(o));

                Toast.makeText(preference.getContext(), "您已经更改网络环境，退出页面APP重新切换环境", Toast.LENGTH_SHORT).show();
            }
            return true;
        }

    }

    @Override
    public void onBackPressed() {
        Object changeValue = SPUtils.get(this, NET_ADDRESS_VALUE_KEY, "1");
        if (!sCurEnv.equalsIgnoreCase(String.valueOf(changeValue))) {
            android.os.Process.killProcess(android.os.Process.myPid());
        } else {
            finish();
        }
    }

    public static boolean isOfficialEnvironment(Context context) {
        Object curEnv = SPUtils.get(context, NET_ADDRESS_VALUE_KEY, "1");
        return "1".equalsIgnoreCase(String.valueOf(curEnv));
    }
}